<?php

namespace app\models;

use app\facade\Redis;
use app\facade\Token;
use app\observer\Event;
use app\observer\Login\LoginHandler;
use Surest\Traits\HasRoles;

class AdminUser extends Base
{
    use HasRoles;
    protected $autoWriteTimestamp = false;
    protected $pk = 'id';
    protected $username_filed = 'username';
    protected $password_filed = 'password';
    protected $hidden = ['password'];

    const ADMIN_USER = 'admin';

    /**
     * 重置用户密码
     * @author baiyouwen
     */
    public function resetPassword($uid, $NewPassword)
    {
        $passwd = $this->encryptPassword($NewPassword);
        $ret = $this->where(['id' => $uid])->update(['password' => $passwd]);
        return $ret;
    }

    # 密码加密
    protected function encryptPassword($password, $salt = '', $encrypt = 'md5')
    {
        return $encrypt($password . $salt);
    }

    /**
     * 数据校验
     * @param string $username
     * @param string $password
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function attempt(string $username, string $password)
    {
        $password = self::encrypt($password);

        return self::where($this->username_filed, $username)->where($this->password_filed, $password)->find();
    }

    public function getLockAttr($value)
    {
        $lock = [
            '1'=>'正常',
            '2'=>'锁定'
        ];
        return array_key_exists($value, $lock) ? $lock[$value] : '未知';
    }

    /**
     * 加密方式
     * @param $password
     * @return string
     */
    public static function encrypt($password)
    {
        return md5($password);
    }
    /**
     * 使之登录
     * @param AdminUser $user
     * @return string
     */
    public function handler(AdminUser $user)
    {
        $token = Token::generateToken();
        $user->admin_id = $user->id;
        $user->token = $token;
        // Redis::set($token, $user);
        // 更新 token
        $this->updateInfo(["token" => $token], [["username", "=", $user->username]]);
        $event = new Event();
        $event->add(new LoginHandler($user));
        $event->trigger();

        return $token;
    }


    /** 更新用户信息 */
    public function updateInfo($data = [], $where = []){
        return Base::updateByWhere($data, $where);
    }

    /**
     * 条件查询
     */
    public function scopeCondition($query)
    {
        $username = request()->param('username');
        $nickname = request()->param('nickname');
        $email = request()->param('email');

        if($username) {
            $query->where('username', 'like', "%$username%");
        }

        if($nickname) {
            $query->where('nickname', 'like', "%$nickname%");
        }

        if($email) {
            $query->where('email', 'like', "%$email%");
        }

        return $query;
    }

    /**
     * 登录时间
     * @param $val
     * @return false|string
     */
    public function getLogintimeAttr($val)
    {
        if($val && is_numeric($val)) {
            return timeFormat($val);
        }
    }

    /**
     * 最近更新时间
     * @param $val
     * @return false|string
     */
    public function getUpdateTimeAttr($val)
    {
        if($val && is_numeric($val)) {
            return timeFormat($val);
        }
    }

    /**
     * 创建时间
     * @param $val
     * @return false|string
     */
    public function getCreateTimeAttr($val)
    {
        if($val && is_numeric($val)) {
            return timeFormat($val);
        }
    }

    /**
     * 检查是否是管理员
     * @param AdminUser $adminUser
     * @return bool
     */
    public static function checkIsAdmin(self $adminUser)
    {
        if($adminUser->username === "admin") {
            return true;
        }
        return false;
    }

    /**
     * 是不是最高管理员
     * 用于前端隐藏删除按钮
     * @return int
     */
    public function getIsAdminAttr()
    {
        if(self::checkIsAdmin($this)) {
            return 1;
        }
        return 0;
    }

    public function users(array $where, $field = '*', $order = [], $pagesize, $page)
    {
        return self::where($where)->field($field)->with('staffInfo')->order($order)->paginate($pagesize, null, ['page' => $page]);
    }

    public function staffInfo()
    {
        return $this->belongsTo('Staff', 'scope_id', 'fid');
    }

    // 获取管理员信息
    public function adminInfo()
    {
        // 检测是否存在用户
        $token = Request()->header('Authorization');
        return self::where("token", $token)->find();
    }
}
